<script setup lang="ts">
  import { ref, watch } from 'vue';
  import { getRoleDetail, editRole } from '@/api/syssetting';
  import { FormInstance, Message } from '@arco-design/web-vue';
  import useLoading from '@/hooks/loading';
  const formRef = ref<FormInstance | null>(null);
  const props = defineProps({
    visible: Boolean,
    formType: Array,
    formData: Object,
    params: Object,
  });
  const { loading, setLoading } = useLoading();

  const formData = ref({
    role_desc: '',
    role_id: '',
    role_name: '',
    role_sort: '',
    role_state: '',
  });

  watch(
    () => props.params.id,
    (newId) => {
      if (newId) {
        getRoleDetail({ role_id: newId }).then((res) => {
          Object.assign(formData.value, res.data);
        });
      }
    },
    { immediate: true, deep: true }
  );

  const emit = defineEmits(['update:visible', 'refresh']);

  const handleSubmit = async () => {
    if (!(await formRef.value?.checkForm())) {
      try {
        setLoading(true);
        const res = await editRole(formRef.value?.formModel);
        Message.success(res.msg);
        emit('update:visible', false);
        setLoading(false);
        emit('refresh');
      } catch (error) {
        setLoading(false);
      }
    } else {
      Message.error('请正确填写表单！');
    }
  };
</script>

<template>
  <a-modal
    title="编辑角色"
    :visible="visible"
    @ok="handleSubmit"
    title-align="start"
    :ok-loading="loading"
    @cancel="
      () => {
        emit('update:visible', false);
      }
    "
  >
    <pro-form
      ref="formRef"
      hiddenBtn
      :form-json="formType"
      :form-data="formData"
    ></pro-form>
  </a-modal>
</template>

<style scoped lang="less"></style>
